angular.module('starter.services', [])

/**
 * A simple example service that returns some data.
 */
.factory('Items', function($http,$window) {
  // Might use a resource here that returns a JSON array
    var scenes;
  // Some fake testing data
  return {
    setScenes: function (data) {
        scenes = data;
    },
    getScenes: function(){
      return scenes;
    },
    all: function($scope,$rootScope) {///js/item.json 项目列表
        var items = [];
        $rootScope.show();
        //alert(items[0].itemName);
        $http.get('http://localhost:3000/item?accessToken='+$window.sessionStorage['loginSuccess']).success(function(data){
            /*items = data;
            //alert(items[0].itemName)
            $scope.items =  items;*/
            $scope.items =  data.program;
            $rootScope.hide();
        });


    },
    /*get: function(itemsId) {
      // Simple index lookup
      return items[itemsId];
    },*/
      getDeviceList: function($scope,$rootScope,itemsId,Items) {///js/device.json  设备列表
          $scope.deviceList = new Array();
          var Device = function(did,deviceName,isOnline,deviceState,timerProgram,selected,mode){//设备对象
              this.did=did;
              this.deviceName=deviceName;
              this.isOnline=isOnline;//
              this.deviceState=deviceState;//开关状态
              this.timerProgram=timerProgram;//定时时间
              this.selected=selected;
              this.mode=mode;

          }

          $http.get('http://localhost:3000/device?progId='+itemsId+'&accessToken='+$window.sessionStorage['loginSuccess']).success(function(data){
              $rootScope.hide();
              if(data.scenes.length>0){
                  $scope.isCheckAll.isdata='1';
              }
              for(var i=0;i<data.scenes.length;i++){

                  var scene = data.scenes[i];//一个设备信息
                  var node = scene.nodes[0].productId==152?scene.nodes[0]:scene.nodes[1];//如果为控制箱ID则返回

                  var binary = node.currentData.data.S//继电器箱设备状态
                  var deviceState='0';
                  if(parseInt(binary)>0){
                      deviceState = '1';//设置设备为开启状态
                  }
                  //判断设备的在线状态，根据返回数据的时间判断
                  var at = node.currentData.at+'000';
                  var currDate = Date.parse(new Date());//当前时间
                  var diff = Number(currDate)-Number(at);
                  var isOnline = '0';
                  if(diff<60*1000){//获取数据是否为一分钟内
                    isOnline = '1';
                  }

                  /*alert(new Date(at));
                  alert(at);*/

                  var timerset='未设置';
                  var snValue = data.scenes[i].snValue;//定时数组名称
                  var timerProgram = data.timerProgram[snValue];
                  //var mode=1;
                  for(var j=0;j<timerProgram.length;j++){//如果循环到的定时模式和数组里的模式相同且key是S1的设为设备的定时设置
                    if(timerProgram[j].mode==node.currentData.data.D&&timerProgram[j].relayAttrKey=='s1'){
                        timerset = timerProgram[j].startTime+' ~ '+timerProgram[j].endTime;
                        break;
                    }
                  }

                  var device = new Device(scene.snValue,scene.title,isOnline,deviceState,timerset,'1',node.currentData.data.D);
                  $scope.deviceList.push(device);

              }
              Items.setScenes(data);
          });
      },
      getDeviceDetail: function($scope,$rootScope,did,scenesdata) {///js/deviceDetail.json 设备详情
          $rootScope.show();
          var DeviceDetail = function(imgUrl,current1,current2,current3,voltage1,voltage2,voltage3,temperature,vibrate,doorSensor){
              this.imgUrl = imgUrl//图片地址
              this.current1 = current1;//电流1
              this.current2 = current2;
              this.current3 = current3;
              this.voltage1 = voltage1;//电压1
              this.voltage2 = voltage2;
              this.voltage3 = voltage3;
              this.temperature = temperature;//温度
              this.vibrate = vibrate;//振动传感器
              this.doorSensor = doorSensor;//门磁传感器
          };
          $http.get('http://localhost:3000/deviceDetail?sceneSn='+did+'&accessToken='+$window.sessionStorage['loginSuccess']).success(function(data){
              $rootScope.hide();
              var node;
              for(var i=0;i<scenesdata.scenes.length;i++){
                  var scene = scenesdata.scenes[i];//一个设备信息
                  if(scene.snValue==did){//找到这个继电器列表所属的设备
                      node = scene.nodes[0].productId==152?scene.nodes[0]:scene.nodes[1];//如果为控制箱节点则返回
                      break;
                  }
              }
              var imgUrl = 'http://www.loiot.com/upload/cam/'+data.currentData.data._url;
              var currentData = node.currentData.data
              var wswi = currentData.WSWI=='1'?'正常':'异常';
              var gswi = currentData.GSWI=='1'?'正常':'异常';
              $scope.deviceDetail = new DeviceDetail(imgUrl, currentData.I1, currentData.I2, currentData.I3, currentData.U1, currentData.U2, currentData.U3, currentData.T, wswi, gswi);

          });
        //return (items[itemsId].item)[deviceID];
    },
      refreshImg: function($scope,$rootScope,did){
          $rootScope.show();
          $http.get('http://localhost:3000/refreshImg?sceneSn='+did+'&accessToken='+$window.sessionStorage['loginSuccess']).success(function(rfdata){
              $rootScope.hide();
              if(rfdata.ra.result.st==1&&rfdata.ra.st==1){//消息发送成功且拍照成功
                $http.get('http://localhost:3000/deviceDetail?sceneSn='+did+'&accessToken='+$window.sessionStorage['loginSuccess']).success(function(data){

                    $scope.deviceDetail.imgUrl = 'http://www.loiot.com/upload/cam/'+data.currentData.data._url;

                });
            }else{
                $scope.deviceDetail.imgUrl = './img/faild.png';
            }
          });
      },
      onOrOff: function($scope,did,state,$ionicPopup){
          if(state=='1'){
              state='255';
          }

        /*var setUrl = 'http://app.sinobaide.com/hu/command/appcmds.action?nodeCmd[0].snValue='+did+'&nodeCmd[0].sw='+state;
          $http({
              method:'POST',
              url:setUrl,
              data:{
              }
          }).success(function(data){
                alert(data);
          });*/
          $http({
              method:'POST',
              url:'http://localhost:3000/onOrOff?snValue='+did+'&sw='+state+'&sss='+did,
              data:{
              }
          }).success(function(data){
            //{"ra":{"st":1,"sd":"ok"},"1001300137100021":1}
              //alert(data.ra.st!=1||data[did]!=1);
              $scope.showAlert = function() {
                  var alertPopup = $ionicPopup.alert({
                      title: '提示',
                      template: '操作失败！',
                      okType:'button1'
                  });
                  alertPopup.then(function(res) {
                      console.log('onandoff');
                  });
              };
              if(data.ra.st!=1||data[did]!=1){
                  $scope.showAlert();
                  for(var i=0;i<$scope.deviceList.length;i++){
                      if($scope.deviceList[i].did==did){
                          if(state=='0'){//如果失败选回以前状态
                          $scope.deviceList[i].deviceState='1';
                          }else{
                              $scope.deviceList[i].deviceState='0';
                          }
                      }
                  }
              }
        });
      },
      changeStateSelected: function($scope,$ionicPopup,isCheckAll1){//关闭全部设备
          var postUrl='http://app.sinobaide.com/hu/command/appcmds.action?';
          var selects = '0';
          var devList = new Array();//存放被选中的设备id
          if(isCheckAll1=='1'){
              selects = '255'
          }
          $scope.showAlert = function(msg) {
              var alertPopup = $ionicPopup.alert({
                  title: '提示',
                  template: msg,
                  okType:'button1'
              });
              alertPopup.then(function(res) {
                  console.log('onandoff');
              });
          };
          var count = 0;
          for(var i=0;i<$scope.deviceList.length;i++){
              if($scope.deviceList[i].selected=='0'){
                  devList.push($scope.deviceList[i].did);
                 postUrl+='nodeCmd['+count+'].snValue='+$scope.deviceList[i].did+'&nodeCmd['+count+'].sw='+selects+'&';
                  count++;
              }
          }
          postUrl = postUrl.substring(0,postUrl.length-1);//删除最后的&符号

          $http({
              method:'POST',
              url:'http://localhost:3000/onOrOffSelects?snValue={'+postUrl.replace(/&/g,'!')+'}',
              //url:postUrl,
              data:{
              }
          }).success(function(data){
              //{"ra":{"st":1,"sd":"ok"},"1001300137100021":1}
              //alert(data.ra.st!=1||data[did]!=1);
              var flag=false;//标记是否有未关闭的设备
              for(var s=0;s<devList.length;s++){
                  if(data[devList[s]]==1){

                      for(var i=0;i<$scope.deviceList.length;i++){
                          if($scope.deviceList[i].did==devList[s]){
                              if(isCheckAll1=='0'){//如果成功改变选中状态
                                  $scope.deviceList[i].deviceState='0';

                              }else{
                                  $scope.deviceList[i].deviceState='1';
                              }
                              $scope.deviceList[i].selected='1';//取消复选框选中
                          }
                      }
                  }else{
                      flag = true;
                  }
              }
              if(flag){
                  $scope.showAlert('出现异常，选中的设备未全部操作成功，请重试！');
                  if(isCheckAll1=='0'){
                      $scope.isCheckAll.ckall='1';//退回开启状态
                  }else{
                      $scope.isCheckAll.ckall='0';//退回关闭状态
                  }
              }
          });

      },
      getSchemeList: function($scope,devId,scenes) {//定时方案
          var timerProgram = scenes.timerProgram[devId];

          $scope.tp1 = new Array();//为每种模式的详细信息创建一个数组
          $scope.tp2 = new Array();
          $scope.tp3 = new Array();

          for(var i=0;i<timerProgram.length;i++){
              if(timerProgram[i].mode=='1'){
                  $scope.tp1.push(timerProgram[i]);
              }else if(timerProgram[i].mode=='2'){
                  $scope.tp2.push(timerProgram[i]);
              }else{
                  $scope.tp3.push(timerProgram[i]);
              }
              timerProgram[i].relayAttrKey = '继电器'+timerProgram[i].relayAttrKey.substring(1,2);
          }
          //var getRelay = function();
          /*$http.get('http://localhost:3000/scheme').success(function(data){
              for(var i=0;i<data.length;i++){
                  data[i].num=i+1;
                  if(data[i].selected){
                      $scope.select = {tid : data[i].tid};
                  }
              }
              $scope.schemeList = data;

          });*/
      },
      schemeChangeMode: function($scope,$ionicPopup,$rootScope,devId,mode){
        //http://app.sinobaide.com/hu/command/appTimeCmd.action?relayTime[0].startTime=11%3A04%3A00&relayTime[0].endTime=11%3A06%3A00
          $rootScope.show();
          var timers;
          if(mode==1){//按选中的不同模式拼接url
              timers = $scope.tp1;
          }else if(mode==2){
              timers = $scope.tp2;
          }else{
              timers = $scope.tp3;
          }
          $scope.showAlert = function(msg) {
              var alertPopup = $ionicPopup.alert({
                  title: '提示',
                  template: msg,
                  okType:'button1'
              });
              alertPopup.then(function(res) {
                  console.log('onandoff');
              });
          };
          var parameters='http://app.sinobaide.com/hu/command/appTimeCmd.action?';
          for(var i=0;i<timers.length;i++){
              var starTtime = timers[i].startTime.replace(/:/g,'%3A');
              var endTime = timers[i].endTime.replace(/:/g,'%3A');
              parameters += 'relayTime['+i+'].startTime='+starTtime+'&relayTime['+i+'].endTime='+endTime+'&';
          }
          //&relayTime[0].mode=1&sceneSn=1001300137100021
          parameters = parameters+'relayTime[0].mode='+mode+'&sceneSn='+devId;
          $http({
              method:'POST',
              url:'http://localhost:3000/schemeChangeMode?snValue={'+parameters.replace(/&/g,'!')+'}',
              //url:postUrl,
              data:{
              }
          }).success(function(data){
              $rootScope.hide();
             if(data.ra.st!=1){
                 $scope.showAlert('设置失败！')
             }
          });
      }
  }
})

    .factory('Relay',function($http,$window){
        var Relay = function(title,attrKey,raId,sceneSn,timerset,relaytate,selected){
            this.title = title;//继电器名称
            this.attrKey = attrKey;//如attrKey为s1，则为1路继电器
            this.raId = raId;//继电器数据库序号字段
            this.sceneSn = sceneSn;//继电器所属设备场景号
            this.timerset = timerset;//定时器设置
            this.relaytate = relaytate;//继电器状态
            this.selected=selected;
        };

       return {
           getRelayList: function($scope,$rootScope,sceneSn,scenesdata) {
               $rootScope.show();
               $scope.relayList = new Array();
               var timerset='未设置';
               var timerProgram;
               var relayStateList='';
               $http.get('http://localhost:3000/relay?sceneSn='+sceneSn+'&accessToken='+$window.sessionStorage['loginSuccess']).success(function(data){
                   $rootScope.hide();
                   var node;
                   for(var i=0;i<scenesdata.scenes.length;i++){
                       var scene = scenesdata.scenes[i];//一个设备信息
                       if(scene.snValue==sceneSn){//找到这个继电器列表所属的设备
                           timerProgram = scenesdata.timerProgram[sceneSn];
                           node = scene.nodes[0].productId==152?scene.nodes[0]:scene.nodes[1];//如果为控制箱ID则返回
                           var binary = parseInt(node.currentData.data.S).toString(2);//继电器状态转换为二进制
                           var len = 8-binary.length;//需要补全的位数
                           for(var z=0;z<len;z++){
                               relayStateList += '0';
                           }
                           relayStateList = relayStateList+binary;//得到8位二进制数
                           /*alert(relayStateList);
                           alert(parseInt(10).toString(2));*/
                           break;
                       }
                   }
                   $scope.isData = false;//判断有无数据
                   if(data.relayName.length==0){
                       $scope.isData = true;
                   }else{
                       $scope.isRelayCheckAll.isdata='1';
                   }
                   for(var s=0;s<data.relayName.length;s++){//循环继电器数组为每一个继电器加上定时时间
                       for(var j=0;j<timerProgram.length;j++){
                           if(timerProgram[j].mode==node.currentData.data.D&&timerProgram[j].relayAttrKey==data.relayName[s].attrKey){//判断此设备的继电器是哪种定时模式
                               timerset = timerProgram[j].startTime+' ~ '+timerProgram[j].endTime;

                           }

                       }

                       var rkey =  data.relayName[s].attrKey;
                       var relaytate='';
                       switch (rkey){//判断是哪个继电器的状态，因为不知道给的数据有没有顺序//如00000011对应s8s7s6s5s4s3s2s1
                           case 's8':
                               relaytate = relayStateList.substring(0,1);
                               break;
                           case 's7':
                               relaytate = relayStateList.substring(1,2);
                               break;
                           case 's6':
                               relaytate = relayStateList.substring(2,3);
                               break;
                           case 's5':
                               relaytate = relayStateList.substring(3,4);
                               break;
                           case 's4':
                               relaytate = relayStateList.substring(4,5);
                               break;
                           case 's3':
                               relaytate = relayStateList.substring(5,6);
                               break;
                           case 's2':
                               relaytate = relayStateList.substring(6,7);
                               break;
                           case 's1':
                               relaytate = relayStateList.substring(7,8);
                               break;
                       }

                       var relay = new Relay(data.relayName[s].title, data.relayName[s].attrKey, data.relayName[s].raId, sceneSn,timerset,relaytate,'1');
                       $scope.relayList.push(relay);

                   }

               });
           },
           relayOnOrOff: function($scope,$ionicPopup,deviceId,index){//deciceId:设备ID，index：作为八路继电器索引0开始

               /*获取2进制的值*/
               var binary='';
               for(var i=$scope.relayList.length-1;i>=0;i--){

                   binary+=$scope.relayList[i].relaytate;
               }
                var state = parseInt(binary,2);//转换为10进制
               $http({
                   method:'POST',
                   url:'http://localhost:3000/onOrOff?snValue='+deviceId+'&sw='+state+'&sss='+deviceId,
                   data:{
                   }
               }).success(function(data){
                   //{"ra":{"st":1,"sd":"ok"},"1001300137100021":1}
                   //alert(data.ra.st!=1||data[did]!=1);
                   $scope.showAlert = function() {
                       var alertPopup = $ionicPopup.alert({
                           title: '提示',
                           template: '操作失败！',
                           okType:'button1'
                       });
                       alertPopup.then(function(res) {
                           console.log('onandoff');
                       });
                   };
                   if(data.ra.st!=1||data[deviceId]!=1){
                       $scope.showAlert();
                       if($scope.relayList[index].relaytate=='0'){//如果失败选回以前状态
                           $scope.relayList[index].relaytate='1';
                       }else{
                           $scope.relayList[index].relaytate='0';
                       }
                   }
               });
           },
           changeRelayStateSelected: function($scope,$ionicPopup,deviceId,isCheckAll){//关闭全部设备
            var devList = new Array();//存放被选中的设备id

            $scope.showAlert = function(msg) {
                var alertPopup = $ionicPopup.alert({
                    title: '提示',
                    template: msg,
                    okType:'button1'
                });
                alertPopup.then(function(res) {
                    console.log('onandoff');
                });
            };
            var binary='';//获取二进制状态
            for(var i=$scope.relayList.length-1;i>=0;i--){
                if($scope.relayList[i].selected=='0'){//找到复选框被勾选的项
                    if($scope.relayList[i].relaytate=='0'&&isCheckAll=='1'){//如果当前状态为关闭状态且批量操作为开启则设置为1
                        binary+='1';
                        devList.push(i);
                    }else{
                        devList.push(i);
                        binary+='0';
                    }
                }else{
                    binary+=$scope.relayList[i].relaytate;
                }
            }
            var state = parseInt(binary,2);//转换为10进制
            $http({
                method:'POST',
                url:'http://localhost:3000/onOrOff?snValue='+deviceId+'&sw='+state+'&sss='+deviceId,
                data:{
                }
            }).success(function(data){
                if(data.ra.st!=1||data[deviceId]!=1){
                    $scope.showAlert('操作失败！');

                    if(isCheckAll=='0'){
                        $scope.isRelayCheckAll.ckall='1';//退回开启状态
                    }else{
                        $scope.isRelayCheckAll.ckall='0';//退回关闭状态
                    }
                }else{
                    for(var ss=0;ss<devList.length;ss++) {
                        if ($scope.relayList[devList[ss]].relaytate == '0'&&isCheckAll=='1') {//如果失败选回以前状态
                            $scope.relayList[devList[ss]].relaytate = '1';
                        } else {
                            $scope.relayList[devList[ss]].relaytate = '0';
                        }
                        $scope.relayList[devList[ss]].selected=='0'
                    }
                }
            });

        },
           getRelayMoreList: function($scope) {

               $http.get('http://localhost:3000/relay').success(function(data){
                   for(var i=0;i<data.length;i++){
                       if(data[i].did==0){

                           for(var j=0;j<data[i].relayList.length;j++){
                               $scope.relayList.push(data[i].relayList[j]);
                           }
                       }
                   }
                   $scope.$broadcast('scroll.infiniteScrollComplete');

               });

           }
       }
    })

.factory('Devices', function(){
    var devices = [
            { id: 0, name: '项目1',item:{id: 0, name: '设备1'} },
            { id: 1, name: '项目2',item:{id: 0, name: '设备2'} },
            { id: 2, name: '项目3',item:{id: 0, name: '设备3'} },
            { id: 3, name: '项目4',item:{id: 0, name: '设备4'} }
    ];
    return {
        all: function() {
            return devices;
        },
        get: function(devicesId) {
            // Simple index lookup
            return devices[devicesId];
        }
    }
})

.factory('LoginService',function($http,$window){//用户登录
        /*function login(loginData,$state) {
            //alert(loginData.userName+"---"+loginData.password);
            $http.post('http://localhost:3000/login',{userName:loginData.userName,password:loginData.password})
            //$http.post('http://api.loiot.com/oauth2/assessTokenLogin?data={"nm":loginData.userName,"pwd":loginData.password,"clientId":"88"}')
                .success(function(result){
                   // alert(result);
                    $window.sessionStorage['loginSuccess'] = result;
                    $state.go('tab.items');
                   // return 'true';
                });
        }*/
        return {
            login: function(loginData,$state,$scope,$ionicPopup){
                //alert(loginData.userName+"---"+loginData.password);
                $http.post('http://localhost:3000/login?userName='+loginData.userName+'&password='+loginData.password+'&clientId='+loginData.clientId)
                    //$http.post('http://api.loiot.com/oauth2/assessTokenLogin?data={"nm":"'+loginData.userName+'","pwd":"'+loginData.password+'","clientId":"'+loginData.clientId+'"}')
                    .success(function(result){
                        // alert(result);
                            $scope.showAlert = function(msg) {
                                var alertPopup = $ionicPopup.alert({
                                    title: '提示',
                                    template: msg,
                                    okType:'button1'
                                });
                                alertPopup.then(function(res) {
                                    console.log('Thank you for not eating my delicious ice cream cone');
                                });
                            };
                        //alert(result);

                        var st = result.ra.st;
                        switch (st)
                        {
                            case 1:
                                $window.sessionStorage['loginSuccess'] = result.data.accessToken;
                                $state.go('tab.items');
                                //$state.go('test');
                                // return 'true';
                                break;
                            case -1:
                                //$scope.status = '提示：登录名不能为空！';
                                $scope.showAlert('用户名不能为空！');
                                break;
                            case -2:
                                //$scope.status = '提示：密码不能为空！';
                                $scope.showAlert('密码不能为空！');
                                break;
                            case -3:
                                //$scope.status = '提示：客户端ID不能为空！';
                                $scope.showAlert('客户端ID不能为空！');
                                break;
                            case -4:
                                //$scope.status = '提示：登录名不存在！';
                                $scope.showAlert('用户名不存在！');
                                break;
                            case -5:
                                //$scope.status = '提示：密码不正确！';
                                $scope.showAlert('密码不正确！');
                                break;
                            case -6:
                                //$scope.status = '提示：客户端ID不存在！';
                                $scope.showAlert('客户端ID不存在！');
                                break;
                            default:
                                //$scope.status = '提示：未知错误！';
                                $scope.showAlert('未知错误！');
                                break;
                        }

                    });
            },
            resetPsw: function($scope,$ionicPopup,$state,oldPassword,newPassword){
                $scope.showAlert = function(msg) {
                    var alertPopup = $ionicPopup.alert({
                        title: '提示',
                        template: msg,
                        okType:'button1'
                    });
                    alertPopup.then(function(res) {
                        $state.go('logOut');
                        console.log('Thank you for not eating my delicious ice cream cone');
                    });
                };
                /*$http.get('http://localhost:3000/resetPsw?oldPassword='+oldPassword+'&newPassword='+newPassword+'&accessToken='+$window.sessionStorage['loginSuccess']).success(function(data){
                    if(data.ra.st==1){
                        $scope.showAlert('密码修改成功，请重新登录！');
                    }else{
                        $scope.showAlert('密码修改失败！请重试！');
                        $state.go('/');
                    }

                });*/
                $http({
                    method:'PUT',
                    url:'http://localhost:3000/resetPsw?oldPassword='+oldPassword+'&newPassword='+newPassword+'&accessToken='+$window.sessionStorage['loginSuccess'],
                    data:{
                    }
                }).success(function(data){
                    if(data.ra.st==1){
                        $scope.showAlert('密码修改成功，请重新登录！');

                    }else{
                        $scope.showAlert('密码修改失败！请重试！');
                        //$state.go('/');
                    }
                });
            }
        }
    });